import requests  

class GrafanaDashboard:
    def __init__(self, grafana_host_url, token) -> None:
        self.grafana_host_url = grafana_host_url
        self.token = token

    def response_print(self, response):
        # 检查请求是否成功  
        if response.status_code in [200, 201]:
            print('请求成功:', response.json())
            return response.json()
        elif response.status_code == 204:
            return True
        else:  
            print(f'请求失败: {response.status_code} - {response.text}')
            return False
        
    def get_alert_rules(self, uid):
        """
          查询仪表盘
        """

        headers = {  
            'Authorization': f'Bearer {self.token}',  
        }  

        grafana_sub_url = "/api/dashboards/uid/"

        grafana_url = self.grafana_host_url + grafana_sub_url + uid

        response = requests.get(grafana_url, headers=headers)

        # 检查请求是否成功  
        response_json = self.response_print(response)

        return response_json
    
    def update_dashboard(self, dashboard_data):
        """
          更新仪表盘
          dashboard_data: 可根据仪表盘-设置-JSON模型内的JS内容获得
        """

        headers = {  
            'Authorization': f'Bearer {self.token}',  
        } 

        # API需要多一层包含
        dashboard_data = {"dashboard" : dashboard_data}

        grafana_sub_url = "/api/dashboards/db"

        grafana_url = self.grafana_host_url + grafana_sub_url

        # 使用requests库发送POST请求  
        response = requests.post(grafana_url, json=dashboard_data, headers=headers)  

        # 检查请求是否成功  
        self.response_print(response)
        # 请求成功: {'folderUid': '', 'id': 4, 'slug': 'e8a5bf-e58d97-e68ea5-e58fa3', 'status': 'success', 'uid': 'ddtztj13cg3y8d', 'url': '/d/ddtztj13cg3y8d/e8a5bf-e58d97-e68ea5-e58fa3', 'version': 7}
        
        return True